/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.base;

import picounit.features.Feature;
import picounit.features.base.exception.UninstiableFeature;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

class FeatureInstantiator {
	private final FeatureResolver featureResolver;

	public FeatureInstantiator(FeatureResolver featureResolver) {
		this.featureResolver = featureResolver;
	}

	@SuppressWarnings("unchecked")
	public <F extends Feature> F instantiate(Class<F> featureClass) {
		Constructor<F> constructor = featureClass.getConstructors()[0];

		List<Object> parameters = new ArrayList<Object>();

		try {
			for (Class<?> parameterType : constructor.getParameterTypes()) {
				parameters.add(featureResolver.getFeature(parameterType));
			}

			return constructor.newInstance(parameters.toArray());
		}
		catch (Exception exception) {
			throw new UninstiableFeature(featureClass, exception);
		}
	}
}